/*
 * @lc app=leetcode.cn id=540 lang=typescript
 *
 * [540] 有序数组中的单一元素
 */

// @lc code=start
function singleNonDuplicate(nums: number[]): number {
  // mid 是否在目标的左边
  const isLeft = (mid: number): boolean => {
    if (mid % 2 === 0 && nums[mid] === nums[mid + 1]) {
      return true;
    } else if (mid % 2 === 1 && nums[mid] === nums[mid - 1]) {
      return true;
    }
    return false;
  };

  let l = 0;
  let r = nums.length - 1;
  while (l < r) {
    let mid = l + ((r - l) >> 1);
    if (isLeft(mid)) {
      l = mid + 1;
    } else {
      r = mid;
    }
  }

  return nums[l];
}
// @lc code=end
